#include<unordered_map>
#include<algorithm>
using std::max;
using std::unordered_map;

struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};



class Solution {
public:
    int rob(TreeNode* root) {
        if (!root) return 0;
        unordered_map<TreeNode*, int> mp;
        return robTree(root, mp);
    }

    int robTree(TreeNode* root, unordered_map<TreeNode*, int>& mp) {
        if (!root) return 0;
        if (mp.find(root) != mp.end()) return mp[root];
        // 不取当前值
        int left = robTree(root->left, mp);
        int right = robTree(root->right, mp);
        int val0 = left + right;
        // 取当前值
        int val1 = root->val;
        if (root->left && root->left->left) val1 += robTree(root->left->left, mp);
        if (root->left && root->left->right) val1 += robTree(root->left->right, mp);
        if (root->right && root->right->left) val1 += robTree(root->right->left, mp);
        if (root->right && root->right->right) val1 += robTree(root->right->right, mp);
        mp[root] = max(val0, val1);
        return mp[root];
    }
};